<template>
    <el-upload
               @click="handleRemove"
               class="avatar-uploader"
               ref="upload"
               :before-upload="beforeAvatarUpload"
               :on-success="handleAvatarSuccess"
               name="img"
               action="/api/upload/uploadImg"
               :limit="1"
               :show-file-list="false"
               list-type="picture-card">

        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
            <Plus />
        </el-icon>

    </el-upload>

    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>
<script  setup>
import { ref, watchEffect } from 'vue'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'

import { ElMessage } from 'element-plus'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)


const handleRemove = (file) => {
    upload.value.handleRemove(file)
}


const handlePictureCardPreview = (file) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}

const handleDownload = (file) => {
    console.log(file)
}



let props = defineProps(['modelValue'])

watchEffect(() => {

    imageUrl.value = props.modelValue

}, {
    flush: 'post'
})




let emit = defineEmits(['update:modelValue'])




const beforeAvatarUpload = (rawFile) => {

    let rawType = ['image/webp', 'image/png', 'image/jpeg', 'image/gif']

    if (!rawType.includes(rawFile.type)) {
        ElMessage.error('上传的文件类型必须是:' + rawType.join(',') + '中的一种')
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        ElMessage.error('文件上传大小不能超过1MB!')
        return false
    }
    return true
}


let imageUrl = ref('')
const handleAvatarSuccess = (response, uploadFile) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
 
    if (response.state) {
  
        emit('update:modelValue', response.imgUrl)

    } else {
        ElMessage.error('上传出错')
    }
}



let upload = ref()



</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>

  